package com.fxm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxm.dao.UserMapper;
import com.fxm.domain.Record;
import com.fxm.domain.User;
import com.fxm.returns.RespCode;
import com.fxm.returns.RespEntity;
import com.fxm.service.RecordService;
import com.fxm.service.UserService;
import com.fxm.utils.TimeUtilCustomize;
import com.fxm.vo.param.IntegralParam;
import com.fxm.vo.param.LoginParam;
import com.fxm.vo.param.OpenParam;
import com.fxm.vo.param.UserParam;
import com.fxm.vo.result.HeadInfoResult;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author fxm
 * @since 2020-12-30
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RecordService recordService;

    @Override
    public RespEntity<User> getUserByOpenId(OpenParam openParam) {
        if (Objects.isNull(openParam)) {
            log.info("参数非法或格式异常，openParam={}", openParam);
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }
        User user = baseMapper.getUserByOpenId(openParam.getOpenid());
        return new RespEntity<User>(RespCode.SUCCESS, user);
    }


    @Override
    public RespEntity updateUser(IntegralParam integralParam) {
        if (Objects.isNull(integralParam)) {
            log.info("参数非法或格式异常，integralParam={}", integralParam);
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }
        try {
            User user = baseMapper.getUserByOpenId(integralParam.getOpenid());
            int integral = user.getIntegral() + integralParam.getNumber();
            user.setIntegral(integral);
            baseMapper.updateUser(user);
            log.info("修改用户积分成功，integral={}", integral);
        } catch (Exception e) {
            return new RespEntity(RespCode.SERVER_ERROR, "修改用户积分失败");
        }
        return new RespEntity(RespCode.SUCCESS);
    }

    @Override
    public RespEntity<HeadInfoResult> headInfo(OpenParam openParam) {
        if (Objects.isNull(openParam)) {
            return new RespEntity<>(RespCode.PARAMETERS_ERROR);
        }

        //每日答题
        Integer today = getToday(openParam.getOpenid());
        //积分排名
        Integer rank = getRank(openParam.getOpenid());
        //胜场
        Integer win = getQuestionWin(openParam.getOpenid());
        //总场次
        Integer total = getQuestionTotal(openParam.getOpenid());

        //数据组装
        HeadInfoResult headInfoResult = new HeadInfoResult();
        headInfoResult.setToday(today);
        headInfoResult.setRank(rank);
        headInfoResult.setWin(win);
        headInfoResult.setTotal(total);

        return new RespEntity<>(RespCode.SUCCESS, headInfoResult);
    }

    /**
     * 每日答题
     * @param openid
     * @return
     */
    private Integer getToday(String openid) {
        String begin = TimeUtilCustomize.parseDateToStr(TimeUtilCustomize.DATE_DAY_FORMAT, new Date());
        String end = TimeUtilCustomize.parseDateToStr(TimeUtilCustomize.DATE_TIME_FORMAT, new Date());

        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Record::getOpenid, openid)
                .eq(Record::getDeleted, 0)
                .between(Record::getCreatedDate, begin, end);

        List<Record> recordList = recordService.list(queryWrapper);

        if (Objects.isNull(recordList)) {
            return 0;
        }

        int today = recordList.size();

        return today;
    }

    /**
     * 积分排名
     * @param openid
     * @return
     */
    private Integer getRank(String openid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getDeleted, 0);
        List<User> userList = baseMapper.selectList(queryWrapper);

        if (Objects.isNull(userList) || CollectionUtil.isEmpty(userList)) {
            return 0;
        }

        List<String> openidList = userList.stream()
                .sorted(Comparator.comparing(User::getIntegral).reversed())
                .map(User::getOpenid)
                .collect(Collectors.toList());

        Map<String, Integer> userMap = Maps.newHashMap();
        for (int i = 0; i < openidList.size(); i++) {
            Integer index = i + 1;
            userMap.put(openidList.get(i), index);
        }

        Integer rank = userMap.get(openid);

        return rank;
    }

    /**
     * 胜场
     * @param openid
     * @return
     */
    private Integer getQuestionWin(String openid) {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Record::getOpenid, openid)
                .eq(Record::getDeleted, 0)
                .eq(Record::getIsRight, "正确");
        List<Record> recordList = recordService.list(queryWrapper);

        if (Objects.isNull(recordList)) {
            return 0;
        }

        int win = recordList.size();

        return win;
    }

    /**
     * 总场次
     * @param openid
     * @return
     */
    private Integer getQuestionTotal(String openid) {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Record::getOpenid, openid)
                .eq(Record::getDeleted, 0);
        List<Record> recordList = recordService.list(queryWrapper);

        if (Objects.isNull(recordList)) {
            return 0;
        }

        int total = recordList.size();

        return total;
    }


}
